//
//  SINATeacherMainViewController.m
//  sinashebao
//
//  Created by  androidlongs on 2017/12/20.
//  Copyright © 2017年  androidlongs. All rights reserved.
//

#import "SINATeacherMainViewController.h"
//#import "WISHomeTabBarView.h"
#import "SINACalendarUtils.h"
#import "SINACircularBeadUtils.h"
#import "SINALabelUtils.h"
#import "LTSCalendarView.h"
#import "SINATecMainItemTableViewCell.h"
#import "SINASubClassModel.h"
#import "SINATecSignNameListViewController.h"
#import "SINATecMainItemAlertTimeTableViewCell.h"
#import "SINATecApprovalManagerViewController.h"
#import "JPUSHService.h"

#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "SINAMainMsgViewController.h"

#define CriticalHeight 30

@interface SINATeacherMainViewController ()<LTSCalendarViewDelegate,LTSCalendarEventSource,UITableViewDelegate,UITableViewDataSource,AMapLocationManagerDelegate>{
    NSMutableDictionary *eventsByDate;
}
@property (weak, nonatomic) IBOutlet UIView *headerView;

//自定义的TabBar
//@property(nonatomic,strong) WISHomeTabBarView *homeTabBarView;
@property (weak, nonatomic) IBOutlet UILabel *currentTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *showCurrentFlagLabel;
@property (weak, nonatomic) IBOutlet UIView *mainContentView;

@property (nonatomic,strong)LTSCalendarView *calendarView;


@property (nonatomic,strong) NSString *currentCourseDate;


@property(nonatomic,assign) double locationLat;
@property(nonatomic,assign) double  locationLng;


@property(nonatomic,strong) NSString  *preUpdateLocationTime;


@property (weak, nonatomic) IBOutlet UIView *msgView;
@property (weak, nonatomic) IBOutlet UIImageView *msgImageView;


// 手指触摸 开始滚动 tableView 的offectY
@property (nonatomic,assign)CGFloat dragStartOffectY;
// 手指离开 屏幕 tableView 的offectY
@property (nonatomic,assign)CGFloat dragEndOffectY;

@property(nonatomic,assign) NSInteger nextClickIndex;

@property(nonatomic,strong) NSMutableArray *dataList;
@property(nonatomic,strong) NSMutableArray *alertDateDataList;
@property(nonatomic,strong) NSMutableArray *coursTimeList;

@property(nonatomic,assign) NSInteger loadingPreTime;

//当前数据模式
//currentFlag ==1 课程
//currentFlag ==2 调课
@property(nonatomic,assign) NSInteger currentFlag;


@property(nonatomic,strong) SINASubClassModel *currentModel;

@property(nonatomic,strong) AMapLocationManager *locationManager;


@end

@implementation SINATeacherMainViewController

- (void)jpushNotificationFunction:(NSNotification *)dic{
    
    DLog(@"－－－－－接收到通知------%@",dic.userInfo[@"pushMsgType"]);
    
    NSString *pushMsgType = dic.userInfo[@"pushMsgType"];
    
    if (pushMsgType!=nil&& [pushMsgType isEqualToString:@"STULEAVEMSG"]) {
        //学生提交请假申请，推送给审批老师
        SINATecApprovalManagerViewController *approvalManagerController = [[SINATecApprovalManagerViewController alloc]initWithNibName:@"SINATecApprovalManagerViewController" bundle:nil];
        approvalManagerController.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:approvalManagerController animated:YES];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initCongfigFunction];
    [self initViewFunction];
    [self initMapFunction];
    
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self loadingSubClassNetData:[SINACalendarUtils currentTimeStr]];
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self showSingleWeekView:YES];
    });
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jpushNotificationFunction:)name:notificationKeyNameTecHome object:nil];
    
    
    
}
-(void)initCongfigFunction{
    self.currentFlag=1;
    self.dataList = [[NSMutableArray alloc]init];
    self.alertDateDataList = [[NSMutableArray alloc]init];
    self.coursTimeList= [[NSMutableArray alloc]init];
    
    [SINACircularBeadUtils makeCircularBead:3 andView:self.showCurrentFlagLabel];
    self.currentTimeLabel.text=[[SINACalendarUtils alloc]getCurrentTime:@"yyyy年MM月"];
    
}
-(void)initViewFunction{
    [SINALabelUtils updateLabel: self.currentTimeLabel andWithString: self.currentTimeLabel.text andWithTextSize:15];
    self.showCurrentFlagLabel.frame=CGRectMake(CGRectGetMaxX(self.currentTimeLabel.frame), CGRectGetMinY(self.showCurrentFlagLabel.frame), CGRectGetWidth(self.showCurrentFlagLabel.frame), CGRectGetHeight(self.showCurrentFlagLabel.frame));
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.msgView.frame = CGRectMake(mainW-80, 20, 80, 48);
    self.msgImageView.frame=CGRectMake(CGRectGetWidth(self.msgView.frame)-12-18, CGRectGetHeight(self.msgView.frame)/2-10, 18, 19);
    self.msgView.backgroundColor=[UIColor clearColor];
    
    if (IS_IPHONE_X) {
        self.headerView.frame=CGRectMake(0, 0, mainW, 88);
        self.currentTimeLabel.frame=CGRectMake(15, 53, 110, 21);
        self.showCurrentFlagLabel.frame=CGRectMake(CGRectGetMaxX(self.currentTimeLabel.frame)+10, 51, 45, 24);
        self.msgView.frame = CGRectMake(mainW-80, 40, 80, 48);
    } else {
        self.headerView.frame=CGRectMake(0, 0, mainW, 64);
        self.currentTimeLabel.frame=CGRectMake(15, 33, 110, 21);
        self.showCurrentFlagLabel.frame=CGRectMake(CGRectGetMaxX(self.currentTimeLabel.frame)+10, 31, 45, 24);
    }
    self.mainContentView.frame=CGRectMake(0,CGRectGetMaxY(self.headerView.frame),mainW,mainH-CGRectGetMaxY(self.headerView.frame));
    
    
    LTSCalendarView *calendarView = [[LTSCalendarView alloc]initWithFrame:CGRectMake(0, 0, mainW, CGRectGetHeight(self.mainContentView.frame)-49)];
    calendarView.delegate = self;
    [self.mainContentView addSubview:calendarView];
    calendarView.frame=CGRectMake(0, 0, mainW, CGRectGetHeight(self.mainContentView.frame));
    ///设置 日历外观 样式 显示一
    self.calendarView = calendarView;
    calendarView.calendar.calendarAppearance.weekDayFormat = LTSCalendarWeekDayFormatSingle;
    
    self.calendarView.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.calendarView.tableView.backgroundColor=[UIColor colorWithHexString:@"#eeeeee"];
    self.calendarView.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.calendarView.tableView.showsVerticalScrollIndicator=NO;
    self.calendarView.tableView.showsHorizontalScrollIndicator=NO;
    
    [self.calendarView.tableView reloadData];
    
    
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.msgView andWithBlick:^(UIView *view) {
        SINAMainMsgViewController
        *settingController = [[SINAMainMsgViewController alloc]initWithNibName:@"SINAMainMsgViewController" bundle:nil];
        settingController.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:settingController animated:YES];
    }];
    
    
    
    
    
}

-(void) initMapFunction{
    [AMapServices sharedServices].apiKey =mapKey;
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //   定位超时时间，最低2s，此处设置为2s
    self.locationManager.locationTimeout =2;
    //   逆地理请求超时时间，最低2s，此处设置为2s
    self.locationManager.reGeocodeTimeout = 2;
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    //   定位超时时间，最低2s，此处设置为10s
    self.locationManager.locationTimeout =10;
    //   逆地理请求超时时间，最低2s，此处设置为10s
    self.locationManager.reGeocodeTimeout = 10;
    // 带逆地理（返回坐标和地址信息）。将下面代码中的 YES 改成 NO ，则不会返回地址信息。

    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        
        if (error)
        {
            DLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            self.preUpdateLocationTime=nil;
            self.locationLat=0;
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        
        DLog(@"location:%@", location);
        
        if (regeocode)
        {
            DLog(@"reGeocode:%@", regeocode);
            self.preUpdateLocationTime=[SINACalendarUtils currentTimeStr];
            
            self.locationLat=location.coordinate.latitude;
            self.locationLng=location.coordinate.longitude;
            
            
        }
    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [super hiniBackItem];
    //    [super hiniNavItem];
    [super initNavBarColorString:@"#01C6AE"];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

-(void)calendarViewNextClick:(LTSCalendarView *)calendarView{
    if (self.nextClickIndex==1) {
        self.nextClickIndex=2;
        [self showAllView:YES];
    } else if (self.nextClickIndex==2){
        self.nextClickIndex=1;
        [self showSingleWeekView:YES];
    }
}

#pragma maek -- LTSCalendarViewDelegate --
- (void)calendarView:(LTSCalendarView *)calendarView didSelectedIndexPath:(NSIndexPath *)indexPath{
    
    DLog(@"%@",indexPath);
}
- (void)calendarDidLoadPage:(LTSCalendarManager *)calendar{
    
}

#pragma mark -- LTSCalendarEventSource --
// 该日期是否有事件
- (BOOL)calendarHaveEvent:(LTSCalendarManager *)calendar date:(NSDate *)date
{
    NSString *key = [[self dateFormatter] stringFromDate:date];
    
    if(eventsByDate[key] && [eventsByDate[key] count] > 0){
        return YES;
    }
    //
    return NO;
}
//当前 选中的日期  执行的方法
- (void)calendarDidDateSelected:(LTSCalendarManager *)calendar date:(NSDate *)date
{
    NSString *key = [[self dateFormatter] stringFromDate:date];
    //self.label.text =  key;
    
    NSArray *events = eventsByDate[key];
    //    self.title = key;
    
    NSString *selectDate = [[self dateYearAndMonFormatter] stringFromDate:date];
    
    self.currentTimeLabel.text=selectDate;
    if (events.count>0) {
        
        //该日期有事件    tableView 加载数据
    }
    
    self.currentCourseDate =[NSString stringWithFormat:@"%llu",[SINACalendarUtils getDateTimeTOMilliSeconds:date]];
    
    DLog(@"SELECT DATE IS %@",[NSString stringWithFormat:@"%llu",[SINACalendarUtils getDateTimeTOMilliSeconds:date]]);
    if (self.currentFlag==1) {
        [self loadingSubClassNetData:[NSString stringWithFormat:@"%llu",[SINACalendarUtils getDateTimeTOMilliSeconds:date]]];
    } else {
        [self loadingAlertSubClassTimeNetData:[NSString stringWithFormat:@"%llu",[SINACalendarUtils getDateTimeTOMilliSeconds:date]]];
    }
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.currentFlag==1) {
        return self.dataList.count;
    }else{
        return self.alertDateDataList.count;
    }
}
//numberOfRowsInSection
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.currentFlag==1) {
        return 110;
    } else {
        return 56;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.currentFlag==1) {
        SINATecMainItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SINATecMainItemTableViewCell"];
        
        if (cell == nil) {
            cell= [[[NSBundle mainBundle]loadNibNamed:@"SINATecMainItemTableViewCell" owner:nil options:nil] firstObject];
            
        }
        cell.itemBlock = ^(SINASubClassModel *itemModel,NSInteger flag) {
            if (flag==0) {
                [self toSignListPage:itemModel];
            } else  if (flag==1){
                DLog(@"调课");
                self.currentFlag=2;
                self.currentModel = itemModel;
                [self loadingAlertSubClassTimeNetData:self.currentCourseDate];
            }else{
                DLog(@"点名");
                [self commitStartSignCourseTimeFunction:itemModel];
            }
            
        };
        SINASubClassModel *model = self.dataList[indexPath.row];
        cell.model=model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        //SINATecMainItemAlertTimeTableViewCell
        SINATecMainItemAlertTimeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SINATecMainItemAlertTimeTableViewCell"];
        
        if (cell == nil) {
            cell= [[[NSBundle mainBundle]loadNibNamed:@"SINATecMainItemAlertTimeTableViewCell" owner:nil options:nil] firstObject];
            
        }
        cell.itemBlock = ^(SINASubClassModel *itemModel,NSInteger flag) {
            if (flag==0) {
                DLog(@"计划调课");
                
                
                //当前课程的开始时间
                NSInteger courStartTime = [self.currentModel.starttime integerValue];
                //当前Item显示的时间
                NSInteger currentStartTime = [itemModel.starttime integerValue];
                //当前时间
                NSInteger currentTime = [[SINACalendarUtils currentTimeStr] integerValue];
                if (currentTime>currentStartTime) {
                    [YPXToastView showToastViewWithText:@"调课时间必须大于当前时间" andDuration:2 andParentView:self.headerView];
                    return;
                }else if(courStartTime==currentStartTime){
                    [YPXToastView showToastViewWithText:@"不能调课至相同的时间段内" andDuration:2 andParentView:self.headerView];
                    return;
                }
                
                if (itemModel.ishas==1) {
                    [YPXToastView showToastViewWithText:@"该时间段有课 不可调课到此时间段" andDuration:2 andParentView:self.headerView];
                    return ;
                }
                
                WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"确定调课到" message:[NSString stringWithFormat:@"%@ - %@",[SINACalendarUtils getDateStringWithTimeStr:itemModel.starttime andFormat:@"MM月dd日 HH:mm"],[SINACalendarUtils getDateStringWithTimeStr:itemModel.endtime andFormat:@"HH:mm"]] sureBtn:@"确定"
                                                                     cancleBtn:@"取消"];
                alertView.resultIndex = ^(NSInteger index) {
                    [self commitAlertCourseTimeFunction:itemModel.starttime endtime:itemModel.endtime cursortime:self.currentCourseDate subName:self.currentModel.name];
                };
                [alertView showXLAlertView];
            }else if (flag==1){
                DLog(@"取消调课");
                self.currentFlag=1;
                [self loadingSubClassNetData:self.currentCourseDate];
            }else{
                [YPXToastView showToastViewWithText:@"暂无可调课时间" andDuration:1 andParentView:self.view];
            }
            
        };
        SINASubClassModel *model = self.alertDateDataList[indexPath.row];
        cell.alertCourseModel = self.currentModel;
        cell.model=model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
}

- (void)createRandomEvents
{
    eventsByDate = [NSMutableDictionary new];
    
    for(int i = 0; i < 30; ++i){
        // Generate 30 random dates between now and 60 days later
        NSDate *randomDate = [NSDate dateWithTimeInterval:(rand() % (3600 * 24 * 60)) sinceDate:[NSDate date]];
        
        // Use the date as key for eventsByDate
        NSString *key = [[self dateFormatter] stringFromDate:randomDate];
        
        if(!eventsByDate[key]){
            eventsByDate[key] = [NSMutableArray new];
        }
        
        [eventsByDate[key] addObject:randomDate];
    }
    
}

- (NSDateFormatter *)dateFormatter
{
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        dateFormatter.dateFormat = @"yyyy.MM.dd";
    }
    
    return dateFormatter;
}

- (NSDateFormatter *)dateYearAndMonFormatter
{
    static NSDateFormatter *dateYearAndMonFormatter;
    if(!dateYearAndMonFormatter){
        dateYearAndMonFormatter = [NSDateFormatter new];
        dateYearAndMonFormatter.dateFormat = @"yyyy年MM月";
    }
    
    return dateYearAndMonFormatter;
}

//当tableView 滚动完后  判断位置
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    CGFloat startSingleOriginY = self.calendarView.calendar.calendarAppearance.weekDayHeight*5;
    
    self.dragEndOffectY  = scrollView.contentOffset.y;
    //0方向向上0 方向向下
    
    //用于判断滑动方向
    CGFloat distance = self.dragStartOffectY - self.dragEndOffectY;
    
    
    if (self.calendarView.tableView.contentOffset.y > CriticalHeight ) {
        if (self.calendarView.tableView.contentOffset.y < startSingleOriginY) {
            if (self.calendarView.tableView.contentOffset.y > startSingleOriginY-CriticalHeight) {
                [self showSingleWeekView:YES];
                return;
            }
            //向下滑动
            if (distance < 0) {
                [self showSingleWeekView:YES];
            }
            
            else [self showAllView:YES];
        }
        
        
    }
    else if (self.calendarView.tableView.contentOffset.y > 0)
        [self showAllView:YES];
    
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    
    CGFloat startSingleOriginY = self.calendarView.calendar.calendarAppearance.weekDayHeight*5;
    
    self.dragEndOffectY  = scrollView.contentOffset.y;
    //0方向向上0 方向向下
    CGFloat distance = self.dragStartOffectY - self.dragEndOffectY;
    
    
    if (self.calendarView.tableView.contentOffset.y>CriticalHeight ) {
        if (self.calendarView.tableView.contentOffset.y<startSingleOriginY) {
            if (self.calendarView.tableView.contentOffset.y>startSingleOriginY - CriticalHeight) {
                [self showSingleWeekView:YES];
                return;
            }
            if (distance<0) {
                [self showSingleWeekView:YES];
            }
            else [self showAllView:YES];
        }
        
        
    }
    else if (self.calendarView.tableView.contentOffset.y > 0)
        [self showAllView:YES];
    
    
    
    
}

//当手指 触摸 滚动 就 设置 上一次选择的 跟当前选择的 周 的index 相等
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.dragStartOffectY  = scrollView.contentOffset.y;
    
    self.calendarView.calendar.lastSelectedWeekOfMonth = self.calendarView.calendar.currentSelectedWeekOfMonth;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
    
    CGFloat offectY = scrollView.contentOffset.y;
    
    CGRect contentFrame = self.calendarView.calendar.contentView.frame;
    
    
    //  当 offectY 大于 滚动到要悬浮的位置
    if ( offectY>self.calendarView.calendar.startFrontViewOriginY) {
        
        
        contentFrame.origin.y = -self.calendarView.calendar.startFrontViewOriginY;
        
        self.calendarView.calendar.contentView.frame = contentFrame;
        
        
        //把 selectedView 插入到 containerView 的最上面
        [self.calendarView.containerView insertSubview:self.calendarView.calendar.selectedWeekView atIndex:996];
        //[self.containerView insertSubview:self.headerDiviView atIndex:999];
        
        // 把tableView 里的 日历视图 插入到 表底部
        [self.calendarView.containerView insertSubview:self.calendarView.calendar.contentView atIndex:0];
        [self.calendarView.calendar setWeekViewHidden:YES toIndex:self.calendarView.calendar.currentSelectedWeekOfMonth-1];
        
    }else{
        self.calendarView.containerView.backgroundColor = self.calendarView.calendar.calendarAppearance.backgroundColor;
        contentFrame.origin.y = 0;
        self.calendarView.calendar.contentView.frame = contentFrame;
        [self.calendarView.calendar setWeekViewHidden:NO toIndex:self.calendarView.calendar.currentSelectedWeekOfMonth-1];
        [self.calendarView.headerView insertSubview:self.calendarView.calendar.selectedWeekView atIndex:1];
        [self.calendarView.headerView insertSubview:self.calendarView.calendar.contentView atIndex:0];
        
    }
    
    
    
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    
}
//回到全部显示初始位置
- (void)showAllView:(BOOL)animate{
    DLog(@"回到全部显示初始位置");
    [self.calendarView.tableView setContentOffset:CGPointMake(0, 0) animated:animate];
    
}
//滚回到 只显示 一周 的 位置
- (void)showSingleWeekView:(BOOL)animate{
    DLog(@"滚回到 只显示 一周 的 位置");
    if (self.nextClickIndex==0) {
        self.nextClickIndex=1;
    }
    
    [self.calendarView.tableView setContentOffset:CGPointMake(0, self.calendarView.calendar.calendarAppearance.weekDayHeight*5-8) animated:animate];
    
}

//点名查询
-(void) toSignListPage:(SINASubClassModel*)model{
    SINATecSignNameListViewController *controller = [[SINATecSignNameListViewController alloc]initWithNibName:@"SINATecSignNameListViewController" bundle:nil];
    controller.hidesBottomBarWhenPushed=YES;
    controller.model = model;
    controller.searchdate=self.currentCourseDate;
    [self.navigationController pushViewController:controller animated:YES];
}


//加载老师课程信息
-(void)loadingSubClassNetData:(NSString*)courTime{
    
    if (![super checkApproveIdent]) {
        return;
    }
    
    self.currentCourseDate = courTime;
    
    [self.dataList removeAllObjects];
    [self.calendarView.tableView reloadData];

    [self startLoading];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    
    [dict setObject:[[SINACommonUserHelper share]getUserModel].userUid forKey:@"teacheruuid"];
    
    [dict setObject:courTime forKey:@"searchdate"];
    
    //[dict setObject:@"1511971200000" forKey:@"searchdate"];
    //self.currentCourseDate=@"1511971200000";
    
    WeakSelf;
    [CXAFNHttpRequestUtils httpGetRequest:[NSString stringWithFormat:@"%@%@",baseUrl,getTodaySubjectByTeacheruuidUrl] withParamters:dict success:^(id responseData) {
        
        NSString *code = responseData[@"code"];
        [weakSelf stopLoading];
        [self.dataList removeAllObjects];
        if ([code isEqualToString:@"1000"]) {
            NSMutableArray *result = responseData[@"content"];
            if (result!=nil&&result.count>0) {
                for (NSInteger i=0; i<result.count; i++) {
                    NSDictionary *dict=result[i];
                    SINASubClassModel *model = [[SINASubClassModel alloc]initWithDict:dict];
                    [self.dataList addObject:model];
                }
            }else{
                [YPXToastView showToastViewWithText:@"暂无课程数据 " andDuration:1  andParentView: self.calendarView];
            }
            
        }else{
            //            NSString *message =responseData[@"message"];
            //            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定"
            //                                                                 cancleBtn:nil];
            //[alertView showXLAlertView];
            //self.noDataLabel.hidden=NO;
            //self.mainContentTableView.hidden=YES;
            [YPXToastView showToastViewWithText:@"加载课程数据异常 " andDuration:1 andParentView:self.calendarView];
        }
        [self loadingTechMonCourseNetData:courTime];
        
        [self.calendarView.tableView reloadData];
        
    } failure:^(NSError *error, NSInteger errCode) {
        //DLog(@"加载 失败  %@ ",error.debugDescription);
        [weakSelf stopLoading];
        //        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"加载数据失败" sureBtn:@"确定"
        //                                                             cancleBtn:nil];
        //[alertView showXLAlertView];
        //        self.noDataLabel.hidden=NO;
        //        self.mainContentTableView.hidden=YES;
        [YPXToastView showToastViewWithText:@"加载课程数据异常 " andDuration:1 andParentView:self.calendarView];
        [self.calendarView.tableView reloadData];
        [self loadingTechMonCourseNetData:courTime];
    }];
}


//加载老师课程 时间信息
-(void)loadingTechMonCourseNetData:(NSString*)courTime{
    
    [self.coursTimeList removeAllObjects];

    [self startLoading];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    //老师uuid
    [dict setObject:[[SINACommonUserHelper share]getUserModel].userUid forKey:@"teacheruuid"];
    ////查询的年月
    [dict setObject:courTime forKey:@"searchdate"];
    
    //[dict setObject:@"1511971200000" forKey:@"searchdate"];
    WeakSelf;
    [CXAFNHttpRequestUtils httpGetRequest:[NSString stringWithFormat:@"%@%@",baseUrl,getSubjectByTeacheruuidUrl] withParamters:dict success:^(id responseData) {
        
        NSString *code = responseData[@"code"];
        [weakSelf stopLoading];
        [self.coursTimeList removeAllObjects];
        if ([code isEqualToString:@"1000"]) {
            NSMutableArray *result = responseData[@"content"];
            if (result!=nil&&result.count>0) {
                for (NSInteger i=0; i<result.count; i++) {
                    NSDictionary *dict=result[i];
                    SINASubClassModel *model = [[SINASubClassModel alloc]initWithDict:dict];
                    [self.coursTimeList addObject:model];
                }
                
                self.calendarView.courListArray = self.coursTimeList;
                self.calendarView.calendar.courListArray = self.coursTimeList;
                [self.calendarView.calendar reloadAppearance];
            }else{
                [self.calendarView.calendar reloadAppearance];
                [YPXToastView showToastViewWithText:@"暂无课程数据 " andDuration:1  andParentView: self.calendarView];
            }
            
        }else{
            //            NSString *message =responseData[@"message"];
            //            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定"
            //                                                                 cancleBtn:nil];
            //[alertView showXLAlertView];
            //self.noDataLabel.hidden=NO;
            //self.mainContentTableView.hidden=YES;
            [YPXToastView showToastViewWithText:@"加载班级数据异常 " andDuration:1 andParentView:self.calendarView];
            [self.calendarView.calendar reloadAppearance];
        }
        
        
        
    } failure:^(NSError *error, NSInteger errCode) {
        //DLog(@"加载 失败  %@ ",error.debugDescription);
        [weakSelf stopLoading];
        //        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"加载数据失败" sureBtn:@"确定"
        //                                                             cancleBtn:nil];
        //[alertView showXLAlertView];
        //        self.noDataLabel.hidden=NO;
        //        self.mainContentTableView.hidden=YES;
        [YPXToastView showToastViewWithText:@"加载课程数据异常 " andDuration:1 andParentView:self.calendarView];
        
        [self.calendarView.calendar reloadAppearance];
    }];
}


//加载老师调课程时间信息
-(void)loadingAlertSubClassTimeNetData:(NSString*)courTime{
    
    if (self.currentModel==nil) {
        return;
    }
    if(self.currentModel.classifyid==nil){
        [YPXToastView showToastViewWithText:@"加载调课时间异常 " andDuration:1 andParentView:self.calendarView];
        [self.alertDateDataList removeAllObjects];
        SINASubClassModel *noTimemodel = [[SINASubClassModel alloc]init];
        noTimemodel.itemType=3;
        [self.alertDateDataList addObject:noTimemodel];
        SINASubClassModel *model = [[SINASubClassModel alloc]init];
        model.itemType=2;
        [self.alertDateDataList addObject:model];
        [self.calendarView.tableView reloadData];
        return;
    }
    self.currentCourseDate = courTime;
    
    [self.alertDateDataList removeAllObjects];

    [self startLoading];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    
    ////老师uuid
    [dict setObject:[[SINACommonUserHelper share]getUserModel].userUid forKey:@"teacheruuid"];
    //班级id
    [dict setObject:self.currentModel.classifyid forKey:@"classifyid"];
    
    
    
    ////查询日期
    [dict setObject:courTime forKey:@"searchdate"];
    
    //[dict setObject:@"1511971200000" forKey:@"searchdate"];
    //self.currentCourseDate=@"1511971200000";
    
    WeakSelf;
    [CXAFNHttpRequestUtils httpGetRequest:[NSString stringWithFormat:@"%@%@",baseUrl,getTimeslotUrl] withParamters:dict success:^(id responseData) {
        
        NSString *code = responseData[@"code"];
        [weakSelf stopLoading];
        [self.alertDateDataList removeAllObjects];
        if ([code isEqualToString:@"1000"]) {
            NSMutableArray *result = responseData[@"content"];
            if (result!=nil&&result.count>0) {
                for (NSInteger i=0; i<result.count; i++) {
                    NSDictionary *dict=result[i];
                    SINASubClassModel *model = [[SINASubClassModel alloc]initWithDict:dict];
                    model.itemType=1;
                    [self.alertDateDataList addObject:model];
                }
            }else{
                [YPXToastView showToastViewWithText:@"暂无可用时间" andDuration:1  andParentView: self.calendarView];
                SINASubClassModel *noTimemodel = [[SINASubClassModel alloc]init];
                noTimemodel.itemType=3;
                [self.alertDateDataList addObject:noTimemodel];
            }
            
        }else{
            SINASubClassModel *noTimemodel = [[SINASubClassModel alloc]init];
            noTimemodel.itemType=3;
            [self.alertDateDataList addObject:noTimemodel];
            //            NSString *message =responseData[@"message"];
            //            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定"
            //                                                                 cancleBtn:nil];
            //[alertView showXLAlertView];
            //self.noDataLabel.hidden=NO;
            //self.mainContentTableView.hidden=YES;
            [YPXToastView showToastViewWithText:@"加载调课时间异常 " andDuration:1 andParentView:self.calendarView];
        }
        
        
        SINASubClassModel *model = [[SINASubClassModel alloc]init];
        model.itemType=2;
        [self.alertDateDataList addObject:model];
        [self.calendarView.tableView reloadData];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self showSingleWeekView:YES];
        });
        
        
        
    } failure:^(NSError *error, NSInteger errCode) {
        DLog(@"加载 失败  %@ ",error.debugDescription);
        [weakSelf stopLoading];
        //        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"加载数据失败" sureBtn:@"确定"
        //                                                             cancleBtn:nil];
        //[alertView showXLAlertView];
        //        self.noDataLabel.hidden=NO;
        //        self.mainContentTableView.hidden=YES;
        [YPXToastView showToastViewWithText:@"加载数据异常 " andDuration:1 andParentView:self.calendarView];
        
        SINASubClassModel *noTimemodel = [[SINASubClassModel alloc]init];
        noTimemodel.itemType=3;
        [self.alertDateDataList addObject:noTimemodel];
        
        SINASubClassModel *model = [[SINASubClassModel alloc]init];
        model.itemType=2;
        [self.alertDateDataList addObject:model];
        [self.calendarView.tableView reloadData];
        
    }];
}


//保存调课信息
-(void)commitAlertCourseTimeFunction:(NSString*)starttime endtime:(NSString*)endtime cursortime:(NSString*)cursortime subName:(NSString*)subName{

    [self startLoading];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    //老师uuid
    
    //老师名称
    [dict setObject: [[SINACommonUserHelper share]getUserModel].userRealName forKey:@"teachername"];
    //课程名称
    if (subName!=nil&&![subName isEqualToString:@""]) {
        [dict setObject:subName forKey:@"syllabusname"];
    }
    
    //原上课的课程表id String syllabusid
    //调课后的开始时间 String starttime
    //调课后的结束时间 String endtime
    //调课后的日期 String cursortime
    [dict setObject:[NSString stringWithFormat:@"%@",self.currentModel.syllabusid] forKey:@"syllabusid"];
    
    //原上课的课程表子表id String syllabusac
    [dict setObject:[NSString stringWithFormat:@"%@",self.currentModel.buildname] forKey:@"buildname"];
    
    [dict setObject:[NSString stringWithFormat:@"%@",self.currentModel.classroom] forKey:@"classroom"];
    
    [dict setObject:[NSString stringWithFormat:@"%@",self.currentModel.syllabusclassid] forKey:@"syllabusac"];
    
    [dict setObject:[NSString stringWithFormat:@"%@",starttime] forKey:@"starttime"];
    [dict setObject:[NSString stringWithFormat:@"%@",endtime] forKey:@"endtime"];
    [dict setObject:[NSString stringWithFormat:@"%@",cursortime] forKey:@"cursortime"];
    
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
    
    WeakSelf;
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,addChangeCursorInfoUrl] withParamters:dict2 success:^(id responseData) {
        
        NSString *code = responseData[@"code"];
        [weakSelf stopLoading];
        [self.coursTimeList removeAllObjects];
        if ([code isEqualToString:@"1000"]) {
            
            [YPXToastView showToastViewWithText:@"调课成功" andDuration:1 andParentView:self.calendarView];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.currentFlag=1;
                [self loadingSubClassNetData:self.currentCourseDate];
            });
            
            
        }else{
            //            NSString *message =responseData[@"message"];
            //            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定"
            //                                                                 cancleBtn:nil];
            //[alertView showXLAlertView];
            //self.noDataLabel.hidden=NO;
            //self.mainContentTableView.hidden=YES;
            [YPXToastView showToastViewWithText:@"调课异常 " andDuration:1 andParentView:self.calendarView];
            
        }
        
        
        
    } failure:^(NSError *error, NSInteger errCode) {
        DLog(@"加载 失败  %@ ",error.debugDescription);
        [weakSelf stopLoading];
        //        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"加载数据失败" sureBtn:@"确定"
        //                                                             cancleBtn:nil];
        //[alertView showXLAlertView];
        //        self.noDataLabel.hidden=NO;
        //        self.mainContentTableView.hidden=YES;
        [YPXToastView showToastViewWithText:@"调课异常 " andDuration:1 andParentView:self.calendarView];
        
    }];
}




//老师点名
-(void)commitStartSignCourseTimeFunction:(SINASubClassModel*)classModel{
    
    
    
    
    //当前时间
    NSInteger currentTime = [[SINACalendarUtils currentTimeStr] integerValue];
    DLog(@"课程点名当前时间是 %ld",(long)currentTime);
    //课程开始时间
    NSInteger courseStartTime = [classModel.starttime integerValue];
    DLog(@"课程点名当前时间是 courseStartTime %ld",(long)courseStartTime);
    //课程结束时间
    NSInteger courseEndTime = [classModel.endtime integerValue];
    
    //开课前50分钟可点名
    NSInteger signStartTime = courseStartTime -1000*courseSignPreTime*60;
//    NSInteger signEndTime = courseStartTime +1000*courseSignPreTime*60;
    
    
    if(currentTime<signStartTime){
        //未到上课时间
        [YPXToastView showToastViewWithText:@"未到上课时间" andDuration:3 andParentView:self.calendarView];
        return;
    }else if (currentTime>=courseStartTime&&currentTime<=courseEndTime){
        //可点名时间中
        
    }else{
        //课程结束
        [YPXToastView showToastViewWithText:@"课程已结束" andDuration:3 andParentView:self.calendarView];
        return;
    }
    
    
    if (classModel.courseLocationLat==0) {
        [YPXToastView showToastViewWithText:@"不在教室范围中" andDuration:3 andParentView:self.calendarView];
        return;
    }
    
    
    
    NSInteger flagUpdateLocationTime=0;
    if (self.preUpdateLocationTime==nil) {
        flagUpdateLocationTime=0;
    } else {
        flagUpdateLocationTime = currentTime -[self.preUpdateLocationTime integerValue];
    }
    if (flagUpdateLocationTime<0) {
        flagUpdateLocationTime=0;
    }
    
    //校验地址
    double courseLat = classModel.courseLocationLat;
    double courseLng = classModel.courseLocationLon;
    
    
    
    if (self.locationLat==0||flagUpdateLocationTime>courseSignUpdate*60*1000) {
        
        //重新获取坐标

        [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
            
            if (error)
            {
                DLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
                [YPXToastView showToastViewWithText:@"位置刷新失败" andDuration:3 andParentView:self.mainContentView];
                if (error.code == AMapLocationErrorLocateFailed)
                {
                    return;
                }
            }
            
            DLog(@"location:%@", location);
            
            if (regeocode)
            {
                
                self.preUpdateLocationTime =[SINACalendarUtils currentTimeStr];
                
                self.locationLat=location.coordinate.latitude;
                self.locationLng=location.coordinate.longitude;
                
                //校验距离
                double flagDistance = [self distanceBetweenOrderBy:courseLat :self.locationLat :courseLng :self.locationLng];
                
                if (flagDistance<=courseSignDistance) {
                    //可签到
                    [YPXToastView showToastViewWithText:@"位置刷新成功 请重新发起点名" andDuration:3 andParentView:self.mainContentView];
                } else {
                    self.locationLat=0;
                    //不可签到
                    [YPXToastView showToastViewWithText:@"不在教室点名范围中" andDuration:3 andParentView:self.mainContentView];
                    
                }
                
            }
        }];
        
        return;
    } else {
        //校验距离
        double flagDistance = [self distanceBetweenOrderBy:courseLat   :self.locationLat :courseLng :self.locationLng];
        
        if (flagDistance<=courseSignDistance) {
            //可点名
        } else {
            self.locationLat=0;
            //不可点名
            [YPXToastView showToastViewWithText:@"不在教室签到范围中" andDuration:3 andParentView:self.mainContentView];
            return;
        }
        
    }

    [self startLoading];
    
    self.loadingPreTime = [[SINACalendarUtils currentTimeStr] integerValue];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    //老师uuid
    
    //原上课的课程表id String syllabusid
    //调课后的开始时间 String starttime
    //调课后的结束时间 String endtime
    //调课后的日期 String cursortime
    [dict setObject:[NSString stringWithFormat:@"%@",classModel.syllabusid] forKey:@"syllabusid"];
    
    [dict setObject:[[SINACommonUserHelper share]getUserModel].userUid forKey:@"teacheruuid"];
    //原上课的课程表子表id String syllabusac
    [dict setObject:[NSString stringWithFormat:@"%@",classModel.buildname] forKey:@"buildname"];
    
    [dict setObject:[NSString stringWithFormat:@"%@",classModel.classroom] forKey:@"classroom"];
    
    [dict setObject:[NSString stringWithFormat:@"%@",classModel.syllabusclassid] forKey:@"syllabusac"];
    
    
    [dict setObject:[NSString stringWithFormat:@"%f",classModel.courseLocationLat] forKey:@"lati"];
    
    [dict setObject:[NSString stringWithFormat:@"%f",classModel.courseLocationLon] forKey:@"lon"];
    
    //老师名称
    [dict setObject: [[SINACommonUserHelper share]getUserModel].userRealName forKey:@"teachername"];
    //课程名称
    if (classModel.name!=nil&&![classModel.name isEqualToString:@""]) {
        [dict setObject:classModel.name forKey:@"syllabusname"];
    }
    
    
    
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
    
    WeakSelf;
    
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,addRollCallInfoUrl] withParamters:dict2 success:^(id responseData) {
        
        NSString *code = responseData[@"code"];
        
        
        NSInteger currentTime = [[SINACalendarUtils currentTimeStr] integerValue];
        NSInteger flagTime = currentTime - self.loadingPreTime;
        if (flagTime>3000) {
            flagTime =0;
        } else {
            flagTime = 3000 - flagTime;
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(flagTime * USEC_PER_SEC)), dispatch_get_main_queue(), ^{

            [weakSelf stopLoading];
            if ([code isEqualToString:@"1000"]) {
                
                [YPXToastView showToastViewWithText:@"发起点名成功" andDuration:3 andParentView:self.calendarView];
                
            }else{
                
                [YPXToastView showToastViewWithText:@"发起点名异常 " andDuration:3 andParentView:self.calendarView];
                
            }
        });
        
        
        
    } failure:^(NSError *error, NSInteger errCode) {
        DLog(@"加载 失败  %@ ",error.debugDescription);
        [weakSelf stopLoading];
        //        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"加载数据失败" sureBtn:@"确定"
        //                                                             cancleBtn:nil];
        //[alertView showXLAlertView];
        //        self.noDataLabel.hidden=NO;
        //        self.mainContentTableView.hidden=YES;
        [YPXToastView showToastViewWithText:@"点名异常 " andDuration:1 andParentView:self.calendarView];
        
    }];
}

-(double)distanceBetweenOrderBy:(double) lat1 :(double) lat2 :(double) lng1 :(double) lng2{
    
    //    lat1=37.737824978298612;
    //    lng1=112.72856526692708;
    //
    //    lat2=37.737949999999998;
    //    lng2=112.72793900000001;
    
    double xDist = (lat1 - lat2);
    
    double yDist = (lng1- lng2);
    
    double distance = sqrt((xDist * xDist) + (yDist * yDist));
    
    DLog("距离 %f",distance);
    
    CLLocation *curLocation = [[CLLocation alloc] initWithLatitude:lat1 longitude:lng1];
    
    CLLocation *otherLocation = [[CLLocation alloc] initWithLatitude:lat2 longitude:lng2];
    
    distance  = [curLocation distanceFromLocation:otherLocation];
    
    DLog("距离 %f",distance);
    return  distance;
}
@end
